<template>
  <div>
    <el-col :span="4" :xs="24">
      <div class="head-container">
        <el-input v-model="treeName" placeholder="请输入查询名称" clearable size="small" prefix-icon="el-icon-search" />
      </div>
      <el-cascader
        ref="cascader"
        v-model="departMajor"
        style="width: 100%; margin-top: 15px"
        :options="departMajorOptions"
        :props="departMajorProps"
        @change="getLeftTree"
      ></el-cascader>
      <div class="head-container" style="margin-top: 15px">
        <el-tree
          ref="tree"
          node-key="id"
          :data="leftTreeOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>
    </el-col>
  </div>
</template>
<script>
import { courseTree } from "@/api/system/juanChapter";
import { chapterTree } from "@/api/system/juanKnowledge";
import { courseTreeList } from "@/api/system/juanCourse";
import { getKnowledgeTreeByQuestion } from "@/api/juan/juanQuestion";
import { getDeptTree } from "@/api/system/user";

export default {
  name: "Leftpanel",
  components: {},
  props: {
    treeType: {
      type: String,
      default: "chapter",
    },
  },
  data() {
    return {
      treeName: undefined, // 过滤字段
      leftTreeOptions: undefined, // el-tree数据
      selectOptions: undefined,
      departMajor: null,
      departMajorOptions: null,
      departMajorProps: {
        //label: 'treeName',
        label: "label",
        value: "id",
        checkStrictly: true
      },
      defaultProps: {
        children: "children",
        label: "treeName",
      },
      cascader: {},
    };
  },
  computed: {
    cascader_info() {
      return JSON.parse(localStorage.getItem("leftPanel"));
    },
  },
  watch: {
    // 根据名称筛选树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
    cascader_info: {
      // 主要处理数据的回填
      handler(val) {
        if (val) {
          this.cascader = val;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getDepartMajorOptions();
  },
  methods: {
    /** 查询课程树 */
    getLeftTree() {
      if(this.departMajor && this.departMajor.length > 0) {
        let id = this.departMajor[this.departMajor.length - 1]

        if (this.treeType === "chapter") {
          courseTree(id).then((response) => {
            this.dealData(response);
          });
        }

        if (this.treeType === "knowledge") {
          chapterTree(id).then((response) => {
            this.dealData(response);
          });
        }

        if (this.treeType === "question") {
          getKnowledgeTreeByQuestion({
            department: id,
          }).then((response) => {
            var ts = response;
            ts = JSON.parse(JSON.stringify(ts).replace(/"nodeName"/g, '"treeName"'));
            this.dealData(ts);
          });
        }
      }
    },

    dealData(response) {
      this.leftTreeOptions = response.data;
      this.$nextTick(() => {
        if (response.data && response.data.length > 0) {
          // 主要处理数据的回填
          if (JSON.stringify(this.cascader)!=="{}") {
            if (this.cascader.path === this.$route.path) {
              this.$refs.tree.setCurrentKey(this.cascader.treeNode.id); // 默认选中
            } else {
              this.$refs.tree.setCurrentKey(response.data[0].id); // 默认选中节点第一个
            }
          } else {
            this.$refs.tree.setCurrentKey(response.data[0].id); // 默认选中节点第一个
          }

          this.selectOptions = this.buildList(response.data);
          let option = {
            treeNode: response.data[0], //选中节点
            departMajor: this.departMajor, // 联级选择器
            selectOptions: this.selectOptions, // 弹窗下拉数据
            path: this.$route.path,
          };
          this.$emit("leftClick", option);
          localStorage.setItem("leftPanel", JSON.stringify(option));
        } else {
          this.$emit("leftClick", null);
          localStorage.removeItem("leftPanel");
        }
      });
    },

    /** 查询树结构 */
    getDepartMajorOptions() {
      getDeptTree().then((response) => {
        this.departMajorOptions = response.data;
        this.renderTree(this.departMajorOptions, 1);
        this.dgTree(this.departMajorOptions, 3);

        let department = null,
          departId = null,
          majorId = null,
          courseId = null;

        if (response.data && response.data.length > 0) {
          department = response.data[0].id;
          const second = response.data[0].children;
          if (second.length > 0) {
            departId = second[0].id;
            const third = second[0].children;

            //三级
            if (third && third.length > 0) {
              majorId = third[0].id;
              this.departMajor = [department, departId, majorId];
              const fourth = third[0].children;

              //四级
              if (fourth && fourth.length > 0) {
                courseId = fourth[0].id;
                this.departMajor = [department, departId, majorId, courseId];
              }
            }
          }
        }
        // 主要处理数据的回填
        if (JSON.stringify(this.cascader) !== "{}") {
          if (this.cascader.path === this.$route.path) {
            this.departMajor = this.cascader.departMajor;
          }
        }
        this.getLeftTree();
      });
    },

    //递归* 添加level
    renderTree(data, level) {
      return data.map((item) => {
        item.level = level;
        if (item.children) {
          this.renderTree(item.children, level + 1);
        }
      });
    },
    dgTree(list) {
      let ts = [3, 4];
      for (let i = 0; i < list.length; i++) {
        if (!list[i].children) {
          if (ts.indexOf(list[i].level) === -1) {
            list.splice(i, 1);
            i--;
            //删完了
            if (!list.length) {
              return true;
            }
          }
        } else {
          let isDelAll = this.dgTree(list[i].children);
          if (isDelAll) i--;
        }
      }
    },

    /** 递归查询课程下拉树选项 */
    buildList(tree) {
      let arr = [];
      for (let i in tree) {
        arr.push(tree[i]);
        if (tree[i].children && tree[i].children.length !== 0) {
          this.buildList(tree[i].children);
        }
      }
      return arr;
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.treeName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      let option = {
        treeNode: data,
        departMajor: this.departMajor,
        selectOptions: this.selectOptions,
        path: this.$route.path,
      };
      this.$emit("leftClick", option);
      localStorage.setItem("leftPanel", JSON.stringify(option));
    },
  },
};
</script>
